package com.xiaoqian.partyembassy.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xiaoqian.partyembassy.R;


/**
 * 项目：SmartHome
 * 创建人：FangZhiXin
 * 时间：2020/4/28 9:12
 * 描述：自定义输入框，
 * 清除文本，密码可见隐藏
 * TextView+EditText+ImageView
 */
public class ItemEditTextView extends RelativeLayout {

    private static final String TAG = "ItemEditTextView";

    private TextView tv_item_name;
    private EditText et_edit_text;
    private ImageView iv_edit_clear;
    private ImageView iv_edit_password;

    public static final int TYPE_NORMAL = 0;
    public static final int TYPE_CLEAR = 1;
    public static final int TYPE_PASSWORD = 2;
    private int editType = TYPE_NORMAL;

    private int inputType;

    private String itemName;
    private String itemHint;
    private static String text;

    private int nameResId;
    private int itemEditClearIconId;
    private int itemEditPswHideIcon;
    private int itemEditPswShowIcon;
    private boolean itemEnable = true;

    private LinearLayout.LayoutParams etParam;
    private int marginLeft;
    private int marginRight;
    private static final int GRAVITY_LEFT = 0;
    private static final int GRAVITY_CENTER = 1;
    private static final int GRAVITY_RIGHT = 2;
    private int gravity = GRAVITY_LEFT;

    public ItemEditTextView(Context context) {
        this(context, null);
    }

    public ItemEditTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ItemEditTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ItemEditTextView, defStyleAttr, 0);
        int nameId = typedArray.getResourceId(R.styleable.ItemEditTextView_itemEditName, 0);
        if (nameId > 0) {
            itemName = getResources().getString(nameId);
        } else {
            itemName = typedArray.getString(R.styleable.ItemEditTextView_itemEditName);
        }
        nameResId = typedArray.getResourceId(R.styleable.ItemEditTextView_itemEditHeadIcon, nameResId);

        int editTextId = typedArray.getResourceId(R.styleable.ItemEditTextView_itemEditText, 0);
        if (editTextId > 0) {
            text = getResources().getString(editTextId);
        } else {
            text = typedArray.getString(R.styleable.ItemEditTextView_itemEditText);
        }
        int hintId = typedArray.getResourceId(R.styleable.ItemEditTextView_itemEditHint, 0);
        if (hintId > 0) {
            itemHint = getResources().getString(hintId);
        } else {
            itemHint = typedArray.getString(R.styleable.ItemEditTextView_itemEditHint);
        }
        itemEditClearIconId = typedArray.getResourceId(R.styleable.ItemEditTextView_itemEditClearIcon, itemEditClearIconId);
        itemEditPswHideIcon = typedArray.getResourceId(R.styleable.ItemEditTextView_itemEditPswHideIcon, itemEditPswHideIcon);
        itemEditPswShowIcon = typedArray.getResourceId(R.styleable.ItemEditTextView_itemEditPswShowIcon, itemEditPswShowIcon);
        inputType = typedArray.getInt(R.styleable.ItemEditTextView_itemInputType, InputType.TYPE_CLASS_TEXT);
        editType = typedArray.getInt(R.styleable.ItemEditTextView_itemEditType, editType);
        marginLeft = (int) typedArray.getDimension(R.styleable.ItemEditTextView_itemEditMarginLeft, marginLeft);
        marginRight = (int) typedArray.getDimension(R.styleable.ItemEditTextView_itemEditMarginRight, marginRight);
        gravity = typedArray.getInt(R.styleable.ItemEditTextView_itemEditGravity, gravity);
        itemEnable = typedArray.getBoolean(R.styleable.ItemEditTextView_itemEnable, itemEnable);
        typedArray.recycle();
        initView();
    }


    private void initView() {
//        View view = inflate(getContext(), R.layout.widget_item_edit_text_layout, null);
        etParam = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
        setGravity(Gravity.CENTER);
        //直接加载布局，省了这里手动添加布局
        View view = LayoutInflater.from(getContext()).inflate(R.layout.widget_item_edit_text_layout, this, false);
        tv_item_name = view.findViewById(R.id.tv_edit_name);
        et_edit_text = view.findViewById(R.id.et_edit_text);
        iv_edit_clear = view.findViewById(R.id.iv_edit_clear);
        iv_edit_password = view.findViewById(R.id.iv_edit_password);
        tv_item_name.setText(itemName);
        et_edit_text.setText(text);
        et_edit_text.setHint(itemHint);
        et_edit_text.setInputType(inputType);
        et_edit_text.setEnabled(itemEnable);
        if (nameResId != 0) {
            Drawable nameDrawable = getResources().getDrawable(nameResId);
            nameDrawable.setBounds(0, 0, nameDrawable.getIntrinsicWidth(), nameDrawable.getIntrinsicHeight());
            tv_item_name.setCompoundDrawables(nameDrawable, tv_item_name.getCompoundDrawables()[1], tv_item_name.getCompoundDrawables()[2], tv_item_name.getCompoundDrawables()[3]);
        }
        if (itemEditClearIconId != 0) {
            iv_edit_clear.setImageResource(itemEditClearIconId);
        }
        if (itemEditPswHideIcon != 0) {
            iv_edit_password.setImageResource(itemEditPswHideIcon);
        }
        setEditGravity(gravity);
        etParam.setMargins(marginLeft, 0, marginRight, 0);
        et_edit_text.setLayoutParams(etParam);
        iv_edit_clear.setVisibility(GONE);
        iv_edit_password.setVisibility(GONE);
        et_edit_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (mListener != null) {
                    mListener.beforeTextChanged(s, start, count, after);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mListener != null) {
                    mListener.onTextChanged(s, start, before, count);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (editType == TYPE_CLEAR || editType == (TYPE_CLEAR | TYPE_PASSWORD)) {
                    iv_edit_clear.setVisibility(et_edit_text.length() > 0 ? VISIBLE : INVISIBLE);
                }
                if (mListener != null) {
                    mListener.afterTextChanged(s);
                }
            }
        });

        iv_edit_clear.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                et_edit_text.setText("");
            }
        });
        iv_edit_password.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setPasswordVisible();
            }
        });
        setEditType(editType);

        addView(view);
    }

    private boolean isPasswordVisible = false;

    private void setPasswordVisible() {
        if (isPasswordVisible) {
            isPasswordVisible = false;
            if (itemEditPswHideIcon != 0) {
                iv_edit_password.setImageResource(itemEditPswHideIcon);
            }
            et_edit_text.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {
            isPasswordVisible = true;
            if (itemEditPswShowIcon != 0) {
                iv_edit_password.setImageResource(itemEditPswShowIcon);
            }
            et_edit_text.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        }
        Editable text = et_edit_text.getText();
        if (text != null) {
            et_edit_text.setSelection(text.length());
        }
    }

    public void setNameText(String name) {
        this.itemName = name;
        tv_item_name.setText(name);
    }

    public void setHint(String itemHint) {
        this.itemHint = itemHint;
        et_edit_text.setHint(itemHint);
    }

    public void setEditText(String string) {
        text = string;
        et_edit_text.setText(string);
        et_edit_text.setSelection(et_edit_text.length());
    }

    public void setItemEnable(boolean enable){
        itemEnable = enable;
        et_edit_text.setEnabled(itemEnable);
    }

    public void setInputType(int type) {
        this.inputType = type;
        et_edit_text.setInputType(type);
    }

    public void setEditType(int editType) {
        this.editType = editType;
        switch (editType) {
            case TYPE_CLEAR:
//                iv_edit_clear.setVisibility(VISIBLE);
                iv_edit_password.setVisibility(GONE);
                iv_edit_clear.setVisibility(et_edit_text.length() > 0 ? VISIBLE : INVISIBLE);
                et_edit_text.setSelection(et_edit_text.length());
                break;
            case TYPE_PASSWORD:
                iv_edit_clear.setVisibility(GONE);
                iv_edit_password.setVisibility(VISIBLE);
//                et_edit_text.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
                if (et_edit_text.length() > 0) {
                    et_edit_text.setSelection(et_edit_text.length());
                }
                break;
            case TYPE_CLEAR | TYPE_PASSWORD:
//                iv_edit_clear.setVisibility(VISIBLE);
                iv_edit_clear.setVisibility(et_edit_text.length() > 0 ? VISIBLE : INVISIBLE);
                et_edit_text.setSelection(et_edit_text.length());
                iv_edit_password.setVisibility(VISIBLE);
                break;
            default:
                iv_edit_clear.setVisibility(GONE);
                iv_edit_password.setVisibility(GONE);
                break;
        }
    }

    public void setEditGravity(int gravity) {
        this.gravity = gravity;
        switch (gravity) {
            case GRAVITY_LEFT:
                et_edit_text.setGravity(Gravity.START);
                break;
            case GRAVITY_CENTER:
                et_edit_text.setGravity(Gravity.CENTER);
                break;
            case GRAVITY_RIGHT:
                et_edit_text.setGravity(Gravity.RIGHT);
                break;
        }
    }

    public String getText() {
        Editable text = et_edit_text.getText();
        if (text != null) {
            return text.toString();
        }
        return "";
    }

    private OnTextChangedListener mListener;

    public void setOnTextChangedListener(OnTextChangedListener listener) {
        mListener = listener;
    }

    public interface OnTextChangedListener {
        void beforeTextChanged(CharSequence s, int start, int count, int after);

        void onTextChanged(CharSequence s, int start, int before, int count);

        void afterTextChanged(Editable s);
    }

    //添加itemEditText自定义属性的双向绑定
    //参考：https://www.jianshu.com/p/c481d1f4e0b6

    /*@BindingAdapter(value = "itemEditText")
    public static void setItemEditText(ItemEditTextView view, String string) {
        EditText editText = view.findViewById(R.id.et_edit_text);
        if (!editText.getText().toString().equals(string)) {
            editText.setText(string);
            editText.setSelection(editText.length());
        }
    }

    @InverseBindingAdapter(attribute = "itemEditText", event = "itemEditTextAttrChanged")
    public static String getItemEditText(ItemEditTextView view) {
        EditText editText = view.findViewById(R.id.et_edit_text);
        return editText.getText().toString();
    }

    @BindingAdapter(value = {"itemTextChanged", "itemEditTextAttrChanged"}, requireAll = false)
    public static void addTextChangedListener(ItemEditTextView view, final BindingCommand<String> textChanged, final InverseBindingListener itemEditTextAttrChanged) {
        EditText editText = view.findViewById(R.id.et_edit_text);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (itemEditTextAttrChanged != null) {
                    itemEditTextAttrChanged.onSelected();
                }
                if (textChanged != null) {
                    textChanged.execute(charSequence.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }*/

}
